package com.example.kwokg.meishi.Activity;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.VideoView;

import com.example.kwokg.meishi.Bean.Content;
import com.example.kwokg.meishi.Constants;
import com.example.kwokg.meishi.R;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.UpdateListener;

public class CollectItem extends AppCompatActivity {

    private SimpleAdapter adapter;
    private ListView lv;
    private List<Map<String, Object>> maps;
    private ImageView iv;
    private VideoView vv;
    private ArrayAdapter<String> arrayAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_collect_item);
        setTitle("收藏");

        //初始化ListView
        initListView();

        //如果没网路则加载缓存
        if (isNetConn()){
            //获取收藏数据
            getData();
        }else{
            setTitle("没网络，来看看缓存吧");
            final List<String> filenames=new ArrayList<>();
            final File[] files = new File(Constants.APP_ROOTPATH).listFiles();
            //本地文件列表
            for (File file : files) {
                filenames.add(file.getName());
            }
            //简单适配器
            arrayAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,filenames);
            lv.setAdapter(arrayAdapter);
            //简单播放
            vv = (VideoView) findViewById(R.id.collect_vv);
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                    vv.setMediaController(new MediaController(CollectItem.this));
                    vv.setVideoURI(Uri.fromFile(files[position]));
                    vv.setVisibility(View.VISIBLE);
                    vv.start();
                }
            });
            lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                    files[position].delete();
                    filenames.remove(position);
                    arrayAdapter.notifyDataSetChanged();
                    return true;
                }
            });

        }


    }

    //数据是否为空
    private void isDataEmpty() {

        if (maps.size()!=0){
            iv.setVisibility(View.GONE);
            lv.setVisibility(View.VISIBLE);
        }else{
            lv.setVisibility(View.GONE);
            iv.setVisibility(View.VISIBLE);
        }
    }




    private void initListView() {
        lv = (ListView) findViewById(R.id.collect_lv);
        iv = (ImageView) findViewById(R.id.collect_iv);
        //点击事件
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Map<String,Object> map=maps.get(position);
                BmobQuery<Content> query=new BmobQuery<>();
                query.getObject(map.get("id").toString(), new QueryListener<Content>() {
                    @Override
                    public void done(Content content, BmobException e) {
                        if (e==null){
                            startActivity(new Intent(CollectItem.this, VideoActivity.class).putExtra("video",content));
                            overridePendingTransition(0,0);
                        }else{
                            Toast.makeText(CollectItem.this, "请检查网络", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });
        //长按点击事件
        lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                Map<String,Object> map=maps.get(position);
                Content content=new Content();
                content.setObjectId(map.get("id").toString());
                content.delete(new UpdateListener() {
                    @Override
                    public void done(BmobException e) {
                        if (e==null){
                            Toast.makeText(CollectItem.this, "删除成功", Toast.LENGTH_SHORT).show();
                            maps.remove(position);
                            adapter.notifyDataSetChanged();
                            isDataEmpty();
                        }
                    }
                });
                return true;
            }
        });
    }

    private void getData() {
        String username = getSharedPreferences("name", MODE_PRIVATE).getString("name", null);
        if (username!=null){
            BmobQuery<Content> query=new BmobQuery<>();
            query.addWhereEqualTo("userMark",username);
            query.findObjects(new FindListener<Content>() {
                @Override
                public void done(List<Content> list, BmobException e) {
                    if (e==null){
                        maps = new ArrayList<>();
                        for ( int i = 0 ; i < list.size() ; i++){
                            Content content=list.get(i);
                            Map<String,Object> map= new HashMap<>();
                            map.put("time",content.getCreatedAt());
                            map.put("title",content.getRecommend_caption());
                            map.put("id",content.getObjectId());
                            maps.add(map);
                        }
                        adapter = new SimpleAdapter(CollectItem.this, maps, R.layout.collect_item,new String[]{"title","time"},new int[]{R.id.collect_title,R.id.collect_time});
                        lv.setAdapter(adapter);
                        isDataEmpty();
                    }
                }
            });
        }else{
            Toast.makeText(CollectItem.this, "请先登录", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this,Login.class));
            overridePendingTransition(0,0);
            finish();
        }
//        final BmobQuery query=new BmobQuery("Content");
//        query.addQueryKeys("recommend_caption");
//        query.setLimit(20);
//        query.findObjectsByTable(new QueryListener<JSONArray>() {
//
//            @Override
//            public void done(JSONArray jsonArray, BmobException e) {
//                if (e==null){
//
//                     try {
//                        for ( int i = 0 ; i < jsonArray.length() ; i++){
//                            JSONObject obj=jsonArray.getJSONObject(i);
//
//                        }
//
//                     } catch (JSONException e1) {
//                            e1.printStackTrace();
//                     }
//                }
//            }
//        });
    }

    //去跳转动画
    @Override
    protected void onPause() {
        super.onPause();
        overridePendingTransition(0,0);
    }

    public boolean isNetConn() {
        ConnectivityManager connMng  = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMng.getActiveNetworkInfo();
        return networkInfo!=null;
    }

}

